<script setup lang="ts">
import type { DatePrickerConfig } from '@/types/pricker';
import { inject, reactive, watchEffect, unref } from 'vue';

// 是否为大屏应用
const largenScreen = inject<boolean>('largenScreen');
// 是否为只读状态
const readOnly = inject<boolean>('readOnly', false);

const props = withDefaults(defineProps<{ modelValue: string; label: string; name: string }>(), {
  modelValue: '',
  label: '',
  name: '',
});

const emit = defineEmits<{
  (e: 'update:model-value', value: string): void;
  (e: 'onConfirm', value: string[]): void;
}>();

const datePrickerConfig: DatePrickerConfig = reactive({
  show: false,
  value: [],
  onConfirm({ selectedValues }) {
    datePrickerConfig.show = false;
    emit('update:model-value', selectedValues.join(''));
    emit('onConfirm', selectedValues);
  },
});

watchEffect(() => {
  datePrickerConfig.value = [props.modelValue.slice(0, 4), props.modelValue.slice(4, 6), props.modelValue.slice(6)];
});

const showPicker = () => {
  if (!unref(readOnly)) {
    datePrickerConfig.show = true;
  }
};

defineExpose({
  setValue(value: DatePrickerConfig['value']) {
    datePrickerConfig.value = value;
  },
});
</script>
<template>
  <van-field
    v-bind="$attrs"
    label-class="u_label"
    :model-value="props.modelValue"
    :is-link="!readOnly"
    readonly
    :name="name"
    :label="label"
    :placeholder="`${label}`"
    :rules="[{ required: true, message: `请选择${label}` }]"
    @click="showPicker"
  />

  <!-- 弹框 -->
  <van-popup
    v-model:show="datePrickerConfig.show"
    position="bottom"
    safe-area-inset-bottom
    round
    :lock-scroll="!largenScreen"
  >
    <van-date-picker
      v-model="datePrickerConfig.value"
      :min-date="new Date(1960, 0, 1)"
      :max-date="new Date(2060, 0, 1)"
      @confirm="datePrickerConfig.onConfirm"
      @cancel="datePrickerConfig.show = false"
    />
  </van-popup>
</template>
<style lang="less" scoped></style>
